package com.jws.jawestshow;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.jws.JwsSerialPort;
import com.jws.thirdlibrary.CxManager;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Rs485Activity extends Activity implements OnClickListener {
    private Spinner uart_baudrate;
    private Button mOpen, mClose, mStartWrite, mStopWrite, mStartRead, mStopRead;
    private CxManager mCxManager;
    private JwsSerialPort mSerialPort = null;
    private OutputStream mOutputStream;
    private InputStream mInputStream;
    private boolean bStopedwrite = false;
    private boolean bStopedread = false;
    protected StringBuilder mSb;
    protected ScrollView scroll;
    protected TextView inner;
    private Rs485Handler mHandler;
    private static final int MSG_DATA_CHANGED = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rs485);
        mCxManager = CxManager.create(this);
        mSb = new StringBuilder();
        scroll = (ScrollView) findViewById(R.id.scrollview);
        inner = (TextView) findViewById(R.id.status);
//		mHandler = new Rs485Handler(BackgroundThread.get().getLooper());
        HandlerThread handlerThread = new HandlerThread("MyBackgroundThread");
        handlerThread.start();
        // 使用 HandlerThread 的 Looper 创建 Handler
        mHandler = new Rs485Handler(handlerThread.getLooper());

// 使用 Handler 在后台线程执行任务
//		mHandler.post(new Runnable() {
//            @Override
//            public void run() {
//                // 在这里执行你的后台任务
//            }
//        });
        uart_baudrate = (Spinner) findViewById(R.id.uart_baudrate);
        mOpen = (Button) findViewById(R.id.open);
        mClose = (Button) findViewById(R.id.close);
        mStartWrite = (Button) findViewById(R.id.start_write);
        mStopWrite = (Button) findViewById(R.id.stop_write);
        mStartRead = (Button) findViewById(R.id.start_read);
        mStopRead = (Button) findViewById(R.id.stop_read);
        mOpen.setOnClickListener(this);
        mClose.setOnClickListener(this);
        mStartWrite.setOnClickListener(this);
        mStopWrite.setOnClickListener(this);
        mStartRead.setOnClickListener(this);
        mStopRead.setOnClickListener(this);

        mStartWrite.setEnabled(false);
        mStopWrite.setEnabled(false);
        mStartRead.setEnabled(false);
        mStopRead.setEnabled(false);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.open:
                if (mSerialPort != null) {
                    mSerialPort.close();
                    mSerialPort = null;
                }
                int Itembaud = uart_baudrate.getSelectedItemPosition();
                String baudrate = uart_baudrate.getItemAtPosition(Itembaud).toString();
                mSerialPort = mCxManager.jwsOpenSerialPort("/dev/ttyS3", Integer.parseInt(baudrate));
                if (mSerialPort != null) {
                    mOutputStream = mSerialPort.getOutputStream();
                    mInputStream = mSerialPort.getInputStream();
                    Toast.makeText(getApplicationContext(), "open SerialPort success", Toast.LENGTH_SHORT).show();

                    mStartWrite.setEnabled(true);
                    mStopWrite.setEnabled(true);
                    mStartRead.setEnabled(true);
                    mStopRead.setEnabled(true);
                } else {
                    Toast.makeText(getApplicationContext(), "open SerialPort fail", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.close:
                if (mSerialPort != null) {
                    bStopedread = true;
                    bStopedwrite = true;
                    mSerialPort.close();
                    mSerialPort = null;
                    mOutputStream = null;
                    mInputStream = null;

                    mStartWrite.setEnabled(false);
                    mStopWrite.setEnabled(false);
                    mStartRead.setEnabled(false);
                    mStopRead.setEnabled(false);
                }
                break;
            case R.id.start_write:
                Startwrite();
                break;
            case R.id.stop_write:
                bStopedwrite = true;
                break;
            case R.id.start_read:
                Startread();
                break;
            case R.id.stop_read:
                bStopedread = true;
                break;
            default:
                break;
        }
    }

    protected void Startwrite() {
        if (mOutputStream == null) {
            return;
        }
        bStopedwrite = false;
        new Thread(new Runnable() {
            public void run() {
                while (!bStopedwrite) {
                    writeSerialPort("rs485");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }).start();
    }

    protected void Startread() {
        if (mInputStream == null) {
            return;
        }
        bStopedread = false;
        new Thread(new Runnable() {
            public void run() {
                while (!bStopedread) {
                    String str = readSerialPort();
                    if (str != null) {
                        mHandler.removeMessages(MSG_DATA_CHANGED, str);
                        Message m = Message.obtain(mHandler, MSG_DATA_CHANGED, str);
                        mHandler.sendMessageAtFrontOfQueue(m);
                    }
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }).start();
    }

    protected boolean writeSerialPort(String cmd) {
        boolean result = true;
        byte[] mBuffer = cmd.getBytes();
        try {
            if (mOutputStream != null) {
                mOutputStream.write(mBuffer);
            } else {
                result = false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            result = false;
        }
        return result;
    }

    protected String readSerialPort() {
        String str = null;
        int size;
        try {
            if (mInputStream == null)
                return null;
            byte[] buffer = new byte[1024];
            size = mInputStream.read(buffer);
            if (size > 0) {
                str = new String(buffer, 0, size);

            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return str;
    }

    @Override
    public void onDestroy() {
        if (mSerialPort != null) {
            mSerialPort.close();
            mSerialPort = null;
            mOutputStream = null;
            mInputStream = null;
        }
        super.onDestroy();
    }

    void PopMessage(final String msg) {
        this.runOnUiThread(new Runnable() {
            public void run() {
                mSb.append(msg);
                mSb.append("\n");
                inner.setText(mSb);
                scroll2Bottom(msg);
            }
        });
    }

    public void scroll2Bottom(final String msg) {
        ScrollView scroll = (ScrollView) findViewById(R.id.scrollview);
        TextView inner = (TextView) findViewById(R.id.status);
        int offset = inner.getMeasuredHeight() - scroll.getHeight();
        if (offset > 0) {
            scroll.scrollTo(0, offset);
        }
    }

    private class Rs485Handler extends Handler {
        public Rs485Handler(Looper looper) {
//            super(looper, null, true);
            super(looper, null);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_DATA_CHANGED:
                    PopMessage((String) msg.obj);
                    break;
            }
        }
    }
}
